package espacokidsadm.modelo.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import espacokidsadm.util.JPAUtil;


public abstract class Dao implements Serializable{

	private static final long serialVersionUID = -1747435462462602678L;

    private EntityManager em = JPAUtil.getEntityManager();

    public Dao() {
    }

    public EntityManager getEm() {
        return em;
    }

    @SuppressWarnings("unchecked")
	public <T> List<T> getList(Class<T> classToCast,String query,Object... values) {
        Query qr = createQuery(query, values);
        return qr.getResultList();
    }

    @SuppressWarnings("unchecked")
	public <T> List<T> getLimitedList(Class<T> classToCast,String query,int limit,Object... values) {
        Query qr = createQuery(query, values);
        qr.setMaxResults(limit);
        return qr.getResultList();
    }

    @SuppressWarnings("unchecked")
	public <T> List<T> getNamedList(Class<T> classToCast,String namedQuery,Object... values) {
        Query qr = em.createNamedQuery(namedQuery);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                Object object = values[i];
                qr.setParameter(i + 1, object);
            }
        }
        return qr.getResultList();
    }

    @SuppressWarnings("unchecked")
	public <T> T getPojo(Class<T> classToCast,String query,Object... values) throws NoResultException {
        Query qr = createQuery(query, values);
        return (T) qr.getSingleResult();
    }

    public <T> T getPojo(Class<T> classToCast,Serializable primaryKey) {
        return em.find(classToCast, primaryKey);
    }


    public int execute(String query,Object... values) {
        Query qr = createQuery(query, values);
        return qr.executeUpdate();
    }


    private Query createQuery(String query, Object[] values) {
        Query qr = em.createQuery(query);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                Object object = values[i];
                qr.setParameter(i + 1, object);
            }
        }
        return qr;
    }

}
